// 全局变量
const DOG_API = 'https://dog.ceo/api/breeds/image/random';
const CAT_API = 'https://api.thecatapi.com/v1/images/search?limit=1';
let currentType = 'both'; // 默认显示猫和狗
let favorites = JSON.parse(localStorage.getItem('petFavorites')) || [];
let isLoading = false;
let cardCount = 0; // 跟踪已创建的卡片数量
let currentCard = null; // 当前正在操作的卡片
let preloadedCards = []; // 存储预加载的卡片
const MIN_PRELOADED_CARDS = 3; // 最少预加载卡片数

// DOM 元素
const cardsContainer = document.querySelector('.cards');
const loadingScreen = document.querySelector('.loading-screen');
const optionCards = document.querySelectorAll('.option-card');
const skipBtn = document.querySelector('.skip-btn');
const likeBtn = document.querySelector('.like-btn');
const favoritesContainer = document.querySelector('.favorites-container');
const emptyFavorites = document.querySelector('.empty-favorites');
const mainPage = document.getElementById('main-page');
const favoritesPage = document.getElementById('favorites-page');
const showFavoritesBtn = document.getElementById('show-favorites');
const backToMainBtn = document.getElementById('back-to-main');

// 获取预览模态框元素
const previewModal = document.querySelector('.preview-modal');
const previewImage = document.querySelector('.preview-image');
const previewCloseBtn = document.querySelector('.preview-close');
const previewDownloadBtn = document.querySelector('.preview-download');

// 初始化
document.addEventListener('DOMContentLoaded', async () => {
    // 确保主页面在开始时是可见的
    mainPage.classList.add('active');
    
    showLoading();
    updateFavoritesUI();
    initializeEventListeners();
    
    try {
        // 预加载多张卡片
        await preloadCards();
        
        // 显示第一张卡片
        showNextCard();
        
        // 隐藏加载屏幕
        hideLoading();
    } catch (error) {
        console.error('初始化卡片失败:', error);
        // 即使加载失败，也要显示界面
        hideLoading();
        
        // 显示错误信息
        alert('加载萌宠图片失败，请检查网络连接后刷新页面');
    }
});

// 显示加载屏幕
function showLoading() {
    isLoading = true;
    loadingScreen.classList.add('visible');
}

// 隐藏加载屏幕
function hideLoading() {
    isLoading = false;
    loadingScreen.classList.remove('visible');
}

// 事件监听初始化
function initializeEventListeners() {
    // 选择宠物类型
    optionCards.forEach(card => {
        card.addEventListener('click', async () => {
            const previousType = currentType;
            
            optionCards.forEach(c => c.classList.remove('active'));
            card.classList.add('active');
            currentType = card.dataset.type;
            
            // 如果类型改变，清空当前卡片并加载新类型的卡片
            if (previousType !== currentType) {
                // 清空现有卡片
                cardsContainer.innerHTML = '';
                
                // 清空预加载队列
                preloadedCards = [];
                
                // 显示加载屏幕
                showLoading();
                
                // 预加载新类型的卡片并显示
                try {
                    await preloadCards();
                    showNextCard();
                    hideLoading();
                } catch (error) {
                    console.error('加载新类型图片失败:', error);
                    hideLoading();
                }
            }
        });
    });
    
    // 跳过按钮
    skipBtn.addEventListener('click', () => {
        const topCard = document.querySelector('.pet-card');
        if (topCard) {
            topCard.classList.add('nope');
            swipeCard(topCard, 'left');
        }
    });
    
    // 喜欢按钮
    likeBtn.addEventListener('click', () => {
        const topCard = document.querySelector('.pet-card');
        if (topCard) {
            topCard.classList.add('like');
            swipeCard(topCard, 'right');
            addToFavorites({
                id: topCard.dataset.id,
                type: topCard.dataset.type,
                url: topCard.querySelector('img').src
            });
        }
    });
    
    // 页面切换
    showFavoritesBtn.addEventListener('click', () => {
        mainPage.classList.remove('active');
        favoritesPage.classList.add('active');
    });
    
    backToMainBtn.addEventListener('click', () => {
        favoritesPage.classList.remove('active');
        mainPage.classList.add('active');
    });
}

// 获取随机宠物图片
async function fetchPetImage() {
    try {
        let data;
        let type;
        
        // 添加超时处理
        const fetchWithTimeout = async (url, options = {}, timeout = 5000) => {
            const controller = new AbortController();
            const id = setTimeout(() => controller.abort(), timeout);
            const response = await fetch(url, { ...options, signal: controller.signal });
            clearTimeout(id);
            return response;
        };
        
        // 根据当前选择决定获取猫/狗/随机
        if (currentType === 'cat') {
            type = 'cat';
            const response = await fetchWithTimeout(CAT_API);
            data = await response.json();
            return { type, url: data[0].url, id: data[0].id };
        } else if (currentType === 'dog') {
            type = 'dog';
            const response = await fetchWithTimeout(DOG_API);
            data = await response.json();
            // 从URL中提取ID
            const id = data.message.split('/').slice(-2).join('_');
            return { type, url: data.message, id };
        } else {
            // 随机选择猫或狗
            const random = Math.random();
            if (random > 0.5) {
                type = 'cat';
                const response = await fetchWithTimeout(CAT_API);
                data = await response.json();
                return { type, url: data[0].url, id: data[0].id };
            } else {
                type = 'dog';
                const response = await fetchWithTimeout(DOG_API);
                data = await response.json();
                const id = data.message.split('/').slice(-2).join('_');
                return { type, url: data.message, id };
            }
        }
    } catch (error) {
        console.error('获取治愈系萌宠图片失败:', error);
        throw error; // 让调用者处理错误
    }
}

// 预加载卡片
async function preloadCards() {
    try {
        // 当卡片数量低于最小值时，加载新卡片
        while (preloadedCards.length < MIN_PRELOADED_CARDS) {
            const petData = await fetchPetImage();
            if (!petData) continue;
            
            const card = document.createElement('div');
            card.className = 'pet-card';
            card.dataset.id = petData.id;
            card.dataset.type = petData.type;
            
            card.innerHTML = `
                <div class="like-badge">治愈</div>
                <div class="nope-badge">换一张</div>
                <img src="${petData.url}" alt="${petData.type}" draggable="false" class="pet-image" onerror="this.onerror=null; alert('图片加载失败，请尝试刷新页面');" />
                <div class="pet-info">
                    <div class="pet-type">
                        <span class="material-symbols-rounded">${petData.type === 'cat' ? 'pets' : 'cruelty_free'}</span>
                        <h3>${petData.type === 'cat' ? '治愈喵星人' : '减压汪星人'}</h3>
                    </div>
                    <span class="material-symbols-rounded">favorite_border</span>
                </div>
            `;
            
            // 将卡片添加到预加载队列中
            preloadedCards.push(card);
            
            cardCount++;
        }
    } catch (error) {
        console.error('预加载卡片失败:', error);
        throw error;
    }
}

// 显示下一张卡片
function showNextCard() {
    // 如果没有预加载的卡片，返回
    if (preloadedCards.length === 0) return;
    
    // 从预加载队列中取出第一张卡片
    const card = preloadedCards.shift();
    
    // 添加到DOM
    if (cardsContainer.firstChild) {
        cardsContainer.insertBefore(card, cardsContainer.firstChild);
    } else {
        cardsContainer.appendChild(card);
    }
    
    currentCard = card;
    
    // 初始化滑动
    initializeSwipe(card);
    
    // 异步加载更多卡片以维持预加载队列
    (async () => {
        try {
            await preloadCards();
        } catch (error) {
            console.error('补充预加载卡片失败:', error);
        }
    })();
    
    return card;
}

// 创建新卡片 - 保留此函数以兼容其他地方的调用
async function addNewCard() {
    if (preloadedCards.length === 0) {
        await preloadCards();
    }
    return showNextCard();
}

// 初始化滑动手势
function initializeSwipe(element) {
    try {
        const hammertime = new Hammer(element, { inputClass: Hammer.TouchMouseInput });
        
        hammertime.get('pan').set({ direction: Hammer.DIRECTION_HORIZONTAL });
        
        let xPos = 0;
        let yPos = 0;
        let rotation = 0;
        
        hammertime.on('pan', (event) => {
            element.classList.add('swiping');
            
            xPos = event.deltaX;
            yPos = event.deltaY / 4; // 减少垂直移动量
            rotation = xPos * 0.05; // 根据位移量计算旋转角度
            
            element.style.transform = `translate(${xPos}px, ${yPos}px) rotate(${rotation}deg)`;
            
            // 显示喜欢/跳过标志
            if (xPos > 80) {
                element.classList.add('like');
                element.classList.remove('nope');
            } else if (xPos < -80) {
                element.classList.add('nope');
                element.classList.remove('like');
            } else {
                element.classList.remove('like', 'nope');
            }
        });
        
        hammertime.on('panend', (event) => {
            element.classList.remove('swiping');
            
            // 如果滑动距离足够远，完成滑动动作
            if (xPos > 150) {
                swipeCard(element, 'right');
                addToFavorites({
                    id: element.dataset.id,
                    type: element.dataset.type,
                    url: element.querySelector('img').src
                });
            } else if (xPos < -150) {
                swipeCard(element, 'left');
            } else {
                // 否则恢复到原位
                element.style.transform = '';
                element.classList.remove('like', 'nope');
            }
        });
        
        // 添加长按保存功能
        let pressTimer;
        const longPressHint = document.querySelector('.long-press-hint');
        
        element.addEventListener('touchstart', () => {
            pressTimer = setTimeout(() => {
                const imgUrl = element.querySelector('img').src;
                downloadImage(imgUrl);
            }, 800);
            
            // 显示长按提示
            setTimeout(() => {
                if (pressTimer) {
                    longPressHint.classList.add('show');
                }
            }, 400);
        });
        
        element.addEventListener('touchend', () => {
            clearTimeout(pressTimer);
            longPressHint.classList.remove('show');
        });
        
        element.addEventListener('touchmove', () => {
            clearTimeout(pressTimer);
            longPressHint.classList.remove('show');
        });
        
        // 添加点击预览功能
        element.addEventListener('click', () => {
            const imgUrl = element.querySelector('img').src;
            showPreview(imgUrl);
        });
    } catch (error) {
        console.error('初始化滑动失败:', error);
    }
}

// 滑动卡片
async function swipeCard(element, direction) {
    // 添加过渡动画
    element.style.transition = 'transform 0.5s ease';
    element.classList.add(direction === 'right' ? 'transition-like' : 'transition-nope');
    
    // 移除卡片并加载新卡片
    setTimeout(async () => {
        element.remove();
        
        try {
            // 只在没有卡片时显示加载屏幕
            if (preloadedCards.length === 0) {
                showLoading();
            }
            
            // 显示下一张预加载的卡片
            showNextCard();
            
            // 隐藏加载屏幕
            hideLoading();
        } catch (error) {
            console.error('显示下一张卡片失败:', error);
            hideLoading();
            
            // 显示简单的错误提示
            if (cardsContainer.children.length === 0) {
                alert('加载新图片失败，请检查网络连接后刷新页面');
            }
        }
    }, 500);
}

// 添加到收藏夹
function addToFavorites(pet) {
    // 检查是否已经收藏过
    const exists = favorites.some(fav => fav.id === pet.id);
    if (!exists) {
        favorites.push(pet);
        localStorage.setItem('petFavorites', JSON.stringify(favorites));
        updateFavoritesUI();
    }
}

// 从收藏夹移除
function removeFromFavorites(id) {
    favorites = favorites.filter(pet => pet.id !== id);
    localStorage.setItem('petFavorites', JSON.stringify(favorites));
    updateFavoritesUI();
}

// 更新收藏夹UI
function updateFavoritesUI() {
    favoritesContainer.innerHTML = '';
    
    if (favorites.length === 0) {
        emptyFavorites.classList.add('visible');
    } else {
        emptyFavorites.classList.remove('visible');
        
        favorites.forEach(pet => {
            const item = document.createElement('div');
            item.className = 'favorite-item';
            item.dataset.url = pet.url;
            item.innerHTML = `
                <img src="${pet.url}" alt="${pet.type}" onerror="this.onerror=null; this.src='data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22100%22 height=%22100%22><rect fill=%22%23f8f8f8%22 width=%22100%22 height=%22100%22/><text fill=%22%23888%22 x=%2250%%22 y=%2250%%22 text-anchor=%22middle%22 dominant-baseline=%22middle%22 font-family=%22sans-serif%22>图片失效</text></svg>';">
                <button class="remove-btn" data-id="${pet.id}">
                    <span class="material-symbols-rounded">close</span>
                </button>
            `;
            favoritesContainer.appendChild(item);
            
            // 添加点击预览功能
            item.addEventListener('click', (e) => {
                if (!e.target.classList.contains('remove-btn') && !e.target.closest('.remove-btn')) {
                    showPreview(pet.url);
                }
            });
            
            // 添加长按保存功能
            let pressTimer;
            const longPressHint = document.querySelector('.long-press-hint');
            
            item.addEventListener('touchstart', (e) => {
                if (!e.target.classList.contains('remove-btn') && !e.target.closest('.remove-btn')) {
                    pressTimer = setTimeout(() => {
                        downloadImage(pet.url);
                    }, 800);
                    
                    // 显示长按提示
                    setTimeout(() => {
                        if (pressTimer) {
                            longPressHint.classList.add('show');
                        }
                    }, 400);
                }
            });
            
            item.addEventListener('touchend', () => {
                clearTimeout(pressTimer);
                longPressHint.classList.remove('show');
            });
            
            item.addEventListener('touchmove', () => {
                clearTimeout(pressTimer);
                longPressHint.classList.remove('show');
            });
        });
        
        // 添加删除收藏的事件监听
        document.querySelectorAll('.remove-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const id = btn.dataset.id;
                removeFromFavorites(id);
            });
        });
    }
}

// 显示预览
function showPreview(imageUrl) {
    previewImage.src = imageUrl;
    previewModal.classList.add('active');
    
    // 预览图下载按钮事件 - 直接在新窗口打开
    previewDownloadBtn.onclick = () => {
        window.open(imageUrl, '_blank');
    };
    
    // 关闭预览按钮事件
    previewCloseBtn.onclick = () => {
        previewModal.classList.remove('active');
    };
    
    // 点击背景关闭预览
    previewModal.onclick = (e) => {
        if (e.target === previewModal) {
            previewModal.classList.remove('active');
        }
    };
}

// 下载图片函数
async function downloadImage(imageUrl) {
    try {
        showLoading();
        
        // 直接打开图片链接而不是使用fetch
        // 这可以绕过CORS限制
        const link = document.createElement('a');
        link.href = imageUrl;
        link.target = '_blank';
        link.download = imageUrl.split('/').pop().split('?')[0] || `pet-image-${Date.now()}.jpg`;
        
        // 在移动设备上，直接打开链接比较可靠
        if (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)) {
            window.open(imageUrl, '_blank');
            hideLoading();
            return;
        }
        
        // 在其他设备上尝试直接下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        hideLoading();
    } catch (error) {
        console.error('下载图片失败:', error);
        hideLoading();
        alert('保存图片失败，请长按图片并选择"保存图片"选项');
    }
}

// 添加全局错误处理
window.onerror = function(message, source, lineno, colno, error) {
    console.error('页面发生错误:', message);
    hideLoading();
    return true;
}; 